package com.neu.ui;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.po.Book;
import com.neu.po.Doctor;
import com.neu.po.Plan;
import com.neu.po.User;
import com.neu.service.BookService;
import com.neu.service.DoctorService;
import com.neu.service.PlanService;
import com.neu.service.UserService;
import com.neu.util.AlipayUtil;
import com.neu.util.MQConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/Plans")
@CrossOrigin(origins = "*")
public class PlansController {

    @Autowired
    PlanService planService;
    @Autowired
    BookService bookService;
    @Autowired
    DoctorService doctorService;
    @Autowired
    UserService userService;

    @GetMapping("/list/{plan_docid}")
    public String list(@PathVariable("plan_docid") int plan_docid, Model m, @RequestParam(value = "page", defaultValue = "1") int page) {
        Map<String, Object> map = new HashMap<>();
        map.put("plan_docid", plan_docid);
        String where = "p.plan_docid = #{m.plan_docid} ORDER BY p.plan_workdate";
        PageHelper.startPage(page, 5);
        List<Plan> list = planService.selectList(where, map);
        PageInfo<Plan> pageInfo = new PageInfo<>(list);
        m.addAttribute("planList", pageInfo);
        return "planlist";
    }

    @GetMapping("/register/{plan_id}")
    public String register(@PathVariable("plan_id") int plan_id, Model m) {
        Plan plan = planService.selectById(plan_id);
        m.addAttribute("plan", plan);
        return "chekplan";
    }

    @GetMapping("/alipay/{plan_id}")
    public String alipay(@PathVariable("plan_id") int plan_id, Model m, HttpServletResponse resp, HttpSession session) {
        Plan plan = planService.selectById(plan_id);
        User user = (User) session.getAttribute("user");
        if (plan.getPlan_bookcount() > 0) {
            AlipayUtil.startPay(resp, UUID.randomUUID().toString() + "_" + plan_id + "_" + user.getId() + "_" + plan.getPlan_docid(), "20", "挂号订单", "医生出诊id-" + plan_id);
            return "";
        } else {
            return "redirect:/Plans/list/" + plan.getPlan_docid();
        }
    }

    @RequestMapping("/pay_jump")
    public String pay_jump(HttpServletRequest request, String out_trade_no, String timestamp, Model m, HttpSession session, String total_amount, String trade_no, HttpServletResponse response) {
        boolean signVerified = AlipayUtil.checkSign(request);
        //支付成功操作   out_trade_no为出诊id
        if (signVerified) {
            System.out.println("支付成功");
            /*插入预约挂号记录*/
            Book book = new Book();
            book.setPlanId(Integer.parseInt(out_trade_no.split("_")[1]));
            book.setUserId(Integer.parseInt(out_trade_no.split("_")[2]));
            Date date = new Date();
            book.setTime(new java.sql.Timestamp(date.getTime()));
            book.setMoney(Double.parseDouble(total_amount));
            book.setState(0);
            book.setTradeno(trade_no);
            System.out.println(book.toString());
            bookService.addBook(book);

            /*修改医生doc_fee诊治人数*/
            Doctor doctor = doctorService.selectById(Integer.parseInt(out_trade_no.split("_")[3]));
            int len_docfee = doctorService.update(doctor);

            /*剩余放号数调整*/
            Plan plan = planService.selectById(Integer.parseInt(out_trade_no.split("_")[1]));
            int len_editPlan = planService.update(plan);

            /*发送挂号成功短信和邮件*/
            Connection connection = null;
            Channel channel_email = null;
            Channel channel_sms = null;
            User user = userService.findById(Integer.parseInt(out_trade_no.split("_")[2]));
            try {
                //5、通过连接工厂获取连接
                connection = MQConnectionUtil.getConnection("127.0.0.1", 5672, "/", "guest", "guest");
                //2、声明通道
                channel_email = connection.createChannel();
                channel_sms = connection.createChannel();
                //3、声明队列
                channel_email.queueDeclare("mq_email", false, false, false, null);
                channel_sms.queueDeclare("mq_sms", false, false, false, null);
                //4、定义消息内容
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String message_email = "";
                Map<String,Object> map = new HashMap<>();
                map.put("plone",user.getPhone());
                String message = "您已成功预约" + sdf.format(plan.getPlan_worktime()) + plan.getDoctor().getDept().getDept_name() + plan.getDoctor().getDoc_name()+ "医生看病，地点" + plan.getDoctor().getDept().getDept_loc();
                map.put("messge",message);
                //5、发布消息（交换机,队列名字）

                channel_email.basicPublish("", "mq_email", null, message_email.getBytes());
                channel_sms.basicPublish("", "mq_sms", null, JSONObject.toJSONString(map).getBytes());
                //System.out.println("[x] Sent'"+message+"'");
                System.out.println("发送成功");
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                try {
                    //6、关闭通道
                    channel_email.close();
                    channel_sms.close();
                    //7、关闭连接
                    connection.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            return "redirect:/book/list?userId=" + Integer.parseInt(out_trade_no.split("_")[2]);//重定向打开个人预约记录页
        } else {
            throw new RuntimeException();
        }
    }

    @RequestMapping("/pay_success")
    public String pay_success(HttpServletRequest request) {
        boolean signVerified = AlipayUtil.checkSign(request);
        if (signVerified) {
            return "success";
        }
        return "fail";
    }

}
